<template>
	<div class="routinesuperrole">
		<el-card>
			<template #header>
				<div class="card-header clearfix">
					<span class="headerTitle">角色管理</span>
					<div class="floatRight">
						<el-button type="primary" v-if="isAuthBtn('add')" @click="onColumnCzBtn({key:'add',data:''})"><i class="fa fa-pencil-square-o"></i>新增</el-button>
					</div>
				</div>
			</template>
			<div style="margin-bottom:10px;">
				<el-button type="primary" size="default" @click="state.uid='';getRoleList();" v-if="state.uid">清除创建用户条件</el-button>
				<el-button type="primary" size="default" @click="state.updateuid='';getRoleList();" v-if="state.updateuid">清除修改用户条件</el-button>
				<el-button type="primary" size="default" @click="state.role_key='';getRoleList();" v-if="state.role_key">清除标识符</el-button>
			</div>
			<div>
				<Table
					ref="tableRef"
					v-bind="state.tableData"
					class="table-demo"
					@pageChange="onTablePageChange"
					@sortHeader="onSortHeader"
					@columnCzBtn="onColumnCzBtn"
					@columnClick="onColumnClick"
				/>
			</div>
		</el-card>
		<!--修改或新增弹窗-->
		<el-dialog
			v-model="state.dtShow"
			:title="state.detailData.role_id?'修改角色':'新增角色'"
			center
		>
			<div>
				<el-form :model="state.detailData" ref="detailDataRef" :rules="rules" label-width="120px" status-icon>
					<el-form-item label="角色名称" prop="role_name">
						<el-input v-model="state.detailData.role_name"  />
					</el-form-item>
					<el-form-item label="角色标识" prop="role_key">
						<el-input v-model="state.detailData.role_key" />
					</el-form-item>
					<el-form-item label="角色排序" prop="order_num">
						<el-input-number v-model="state.detailData.order_num" />
					</el-form-item>
					<el-form-item label="角色备注" prop="remark">
						<el-input :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" v-model="state.detailData.remark" />
					</el-form-item>
					<el-form-item label="角色状态" prop="status">
						<el-radio-group v-model="state.detailData.status">
							<el-radio label="0"  border>正常</el-radio>
							<el-radio label="1"  border>禁用</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="数据权限" prop="status">
						<el-select
							v-model="state.detailData.data_scope"
							:multiple="false"
							placeholder="Select"
							style="width: 150px"
						>
						<el-option
						  value="1"
						  label="全部数据"
						/>
						<el-option
						  value="2"
						  label="仅个人数据"
						/>
						</el-select>
					</el-form-item>
					<el-form-item label="菜单权限" prop="keys">
						<el-tree v-if="state.dtShow"
						ref="treeRef"
						:data="state.menuList"
						:default-checked-keys="state.detailData.defaultKey"
                		:default-expand-all	="true"
						@check="mcheck"
						show-checkbox
						node-key="id"
						:props="{ children: 'children', label: 'label', class: customNodeClass }"
						/>
						
					</el-form-item>
				</el-form>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.dtShow = false;state.btnloading=false;">取消</el-button>
					<el-button type="primary" @click="queding" :loading="state.btnloading" :disabled="state.btnloading">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { toRefs,ref, reactive,onMounted, defineComponent,defineAsyncComponent } from 'vue';
import { useRouter } from 'vue-router'
import { userApi } from '/@/api/user';
import { pageInfo } from '/@/api';
import { ElNotification, ElMessage ,ElMessageBox ,FormRules,ElTree} from 'element-plus'
import { isModification } from '/@/utils/kingmin';//去重
import commonFunction from '/@/utils/commonFunction';//复制
const { copyText } = commonFunction();

// 引入组件
const Table = defineAsyncComponent(() => import('/@/components/table/index.vue'));
// 定义变量内容
const tableRef = ref<RefType>();

import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
const stores = useUserInfo();
const { userInfos } = storeToRefs(stores);

const detailDataRef=ref();
const treeRef = ref<InstanceType<typeof ElTree>>()
const router = useRouter();

const state = reactive({
	roleBtn:router.currentRoute.value.meta.roleBtn,
	loading:true,
	tbloading:true,
	btnloading:false,
	dataList:[],
	pages: {
        isAll: false,
        pageCount: 0,
        pageSize: 0,
        recordCount: 0,
        pno: 1
	  },
	pageInfo:{
		tbhdList:[],
	},
	detailShow:false,
	details:"",
	role_key:"",
	uid:"",
	updateuid:"",
	orderBy:"",
	menuList:[],
	dtShow:false,
	detailData:{
		role_id:'',
		role_name:'',
		role_key:'',
		order_num:100,
		data_scope:'2',
		status:"0",
		remark:"",
		keys:[],
		defaultKey:[]
	},
	originalData:{},//原始数据
	treeData:[],
	istree:false,
	tableData:{
		data: [],// 列表数据（必传）
		// 表头内容（必传，注意格式）
		header: [],
		// 配置项（必传）
		config: {
			total: 0, // 列表总数
			loading: true, // loading 加载
			isBorder: false, // 是否显示表格边框
			isSerialNo: false, // 是否显示表格序号
			isSelection: true, // 是否显示表格多选
			isExcel: true, // 是否可以导出
			excelName:"角色列表"
		},
		btn:[]
	},
	czBtn:["editor","del"]
});
const rules = reactive<FormRules>({
	role_name: [
		{ required: true, message: '请输入角色名称', trigger: 'blur' },
		{ min: 3, max:12, message: '最少4个字符,最多12个字符', trigger: 'blur' },
	],
	role_key: [
		{ required: true, message: '请输入角色标识', trigger: 'blur' },
		{ min: 3, max:12, message: '最少4个字符,最多12个字符', trigger: 'blur' },
	],
	keys: [
		{ required: true, message: '请选择角色菜单权限', trigger: 'blur' },
	],
	status: [
		{ required: true, message: '请选择角色权限', trigger: 'blur' },
	]
	
});
const mcheck=(e, i)=>{
  if(i.halfCheckedKeys.length>0){
	  state.treeData=i.halfCheckedKeys.concat(i.checkedKeys)
  }else{
	  state.treeData=i.checkedKeys
  }
  state.istree=true;
	
}
const customNodeClass = (data, node) => {
  if (data.isPenultimate) {
    return 'is-penultimate'
  }
  return null
}

const queding=()=>{
	let data=JSON.parse(JSON.stringify(state.detailData));
	if(state.istree){
		data.keys=state.treeData;
		state.detailData.keys=state.treeData;
	}
	detailDataRef.value.validate((valid) => {
		if (valid) {
			// console.log(state.detailData)
			// 修改
			state.btnloading=true;
			if(state.detailData.role_id){
				let dt=isModification(data,state.originalData);
				// let dt=state.detailData;
				if(Object.values(dt).length>0){
					dt.role_id=state.detailData.role_id;
					upDataFun(dt);
				}else{
					ElMessage({message:'没有要修改的数据',type:"warning"});
					state.dtShow=false;
					state.btnloading=false;
				}
				// console.log(dt)
			}else{
				addDataFun(data);
			}			
		}else{
			ElMessage({message:'请检查数据,有必填项未填写',type:"warning"});
		}
	})
}
// 新增
const addDataFun=(dt)=>{
	if(!dt){
		ElMessage.error('修改的数据为空');
		return false;
	}
	userApi('addRoleDetail',dt).then(res=>{
		// console.log(res)
		ElMessage({message:res.msg?res.msg:"操作成功",type:"success"});
		state.dtShow=false;
		state.btnloading=false;
		getRoleList();
	})
	.catch(res=>{
		if(res.code!=450000){
			ElMessageBox.confirm(res.msg, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
			.then(() => {})
			.catch(() => {});
			state.btnloading=false;
		}
	})
}
// 修改
const upDataFun=(dt)=>{
	if(!dt){
		ElMessage.error('修改的数据为空');
		return false;
	}
	userApi('upRoleDetail',dt).then(res=>{
		// console.log(res)
		ElMessage({message:res.msg?res.msg:"操作成功",type:"success"});
		state.dtShow=false;
		state.btnloading=false;
		getRoleList(state.pages.pno);
	})
	.catch(res=>{
		if(res.code!=450000){
			ElMessageBox.confirm(res.msg, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
			.then(() => {})
			.catch(() => {});
			state.btnloading=false;
		}
	})
}
// 表单点击回调
const onColumnClick = (row: EmptyObjectType) => {
	if(row.key=='sort'){
		state.orderBy={
			order:row.data.order,
			prop:row.data.prop
		}
		getRoleList();
	}
	let item=row.item,data=row.data;
	if(item.type=='link'||item.type=='user'){
		if(item.prop=='role_key'){
			state.role_key=data.role_key;
			getRoleList();
		}
		if(item.prop=='createUser'){
			state.uid=data.create_by;
			getRoleList();
		}
		if(item.prop=='updateUser'){
			state.updateuid=data.update_by;
			getRoleList();
		}
	}
	// getTableData();
};
// 表单操作回调
const onColumnCzBtn = (row: EmptyObjectType) => {
	let type=row.key;
	let item=row.data;
	if(type=='editTable'){
		// console.log(item)
		let dt={
			[row.data.item.prop]:row.data.row[row.data.item.prop],
			role_id:row.data.row['role_id']
		}
		if(row.data.row[row.data.item.prop]!=row.data.originalData){
			upDataFun(dt);
			// console.log(dt)
		}
	}
	if(type=='editor'){
		state.originalData=item;//赋值原始数据
		if(state.menuList.length==0){
			getMenuList();
		}
		state.detailData={
			role_id:item.role_id,
			role_name:item.role_name,
			role_key:item.role_key,
			order_num:item.order_num,
			data_scope:item.data_scope,
			status:item.status,
			remark:item.remark,
			keys:item.keys,
			defaultKey:item.defaultKey
		}
		state.dtShow=true;
	}
	if(type=='add'){
		if(state.menuList.length==0){
			getMenuList();
		}
		state.dtShow=true;
		state.detailData={
			role_id:'',
			role_name:'',
			role_key:'',
			order_num:100,
			data_scope:'2',
			status:"0",
			remark:"",
			defaultKey:[],
			keys:[]
		}
	}
	if(type=='del'){
		ElMessageBox.confirm(
			'确定删除角色['+item.role_name+']吗?',
			'提示',
			{
			confirmButtonText: '删除',
			cancelButtonText: '取消',
			type: 'warning',
			}
		)
		.then(() => {
			let dt={
				role_id:item.role_id,
				isdel:1
			}
			if(item.create_by=='admin'){
				ElMessage({
					type: 'error',
					message: '不能删除系统创建的角色',
				})
			}else{
				upDataFun(dt);
			}
			//  console.log(dt)
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			})
		})
	}
	if(type=='delAll'){
		ElMessageBox.confirm(
			'确定删除所选择的角色吗?',
			'提示',
			{
			confirmButtonText: '删除',
			cancelButtonText: '取消',
			type: 'warning',
			}
		)
		.then(() => {
			let list=[];
			for(let p of item){
				if(p.create_by=='admin'){
					ElMessage({
						type: 'error',
						message: '不能删除系统创建的角色',
					})
					return false;
				}
				list.push(p.role_id);
			}
			let dt={
				//  console.log(dt)
				delList:list,
				isdel:1
			}
			upDataFun(dt);
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			})
		})
	}
	state.istree=false;
	// getTableData();
};
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
	// state.tableData.param.pageNum = page.pageNum;
	// state.tableData.param.pageSize = page.pageSize;
	// getTableData();
	state.pages.pageSize=page.pageSize;
	getRoleList(page.pno);
};
// 拖动显示列排序回调
const onSortHeader = (data: TableHeaderType[]) => {
	state.tableData.header = data;
};

// 获取页面前置
const getpageInfo=()=>{
	pageInfo('role').then(res=>{
		//  console.log(res)
		state.pageInfo.tbhdList=res.tbhdList;
		state.tableData.header=res.tbhdList;
		let btn=[];
		for(let p of state.czBtn){
			if(isAuthBtn(p)){
				btn.push(p);
			}
		}
		state.tableData.btn=btn;
		getRoleList();
	})
}
// 获取菜单列表
const getMenuList=()=>{
	userApi('menuList',{}).then(res=>{
		 state.menuList=res;
		// state.pageInfo.tbhdList=res.tbhdList;
		// getRoleList();
	})
}
// 获取角色列表
const getRoleList=(pno:string)=>{
	state.tbloading=true;
	state.tableData.config.loading =true;
	if(!pno){
		pno=1;
	}
	const dt={
		pages:{
			pno:pno,
			pageSize:state.pages.pageSize
		},
		data:{
			role_key:state.role_key,
			create_by:state.uid,
			update_by:state.updateuid,
			orderBy:state.orderBy,
		}
	};
	userApi('roleList',dt).then(res=>{
		state.dataList=res.list;
		state.pages=res.pages;
		state.tbloading=false;
		state.tableData.data=res.list;
		state.tableData.config.total=res.pages.recordCount;
		state.tableData.config.loading = false;
	})
}
// 权限判断
const isAuthBtn = (e:string) => {
	let auth=false;
	if(e){
		for(let p of state.roleBtn){
			if(p==e){
				auth=true;
			}
		}
	}
	return auth;
};
// 判断是否可以修改创始人资料
const isAdminBtn = (item="") => {
	let auth=false;
	if(item){
		if(item.role_key=='admin'){
			if(userInfos.value.role!='admin'){
				auth= true;
			}
		}
	}
	return auth;
};
// 跳转
const tourl = (e) => {
	router.push(e);
};

onMounted(()=>{
      // 获取当前路由实例参数
    //   console.dir(router.currentRoute.value.query.id);
    //   console.dir(router.currentRoute.value.meta.roleBtn);
	  if(!isAuthBtn('index')){
		  router.push('/401');
	  }else{
		  //操作函数
		  getpageInfo()
	  }
})
</script>

<style scoped lang="scss">
	.routinesuperrole{
		padding:5px;
	}
	:deep(.is-penultimate) {
		.el-tree-node__children {
			padding-left: 60px;
			white-space: pre-wrap;
			line-height: 12px;
			.el-tree-node {
				display: inline-block;
			}
			.el-tree-node__content {
				padding-left: 5px !important;
				padding-right: 5px;
				.el-tree-node__expand-icon {
					display: none;
				}
			}
		}
	}
</style>
